package it.netsphere.nswing.util;



import it.redstar.annotated.swing.IComboIdentifier;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * used to read configuration fromproperties files and to be used in HComboBox
 * 
 * @author alberto.goldoni
 *
 */

public final class ComboItem  implements IComboIdentifier

{
	private int id;
	private String description;
	
	public int getComboId(){	return id;}
	public void setComboId(int id){	this.id = id;}
	public String getDescription(){	return description;}
	public void setDescription(String description){	this.description = description;}

	@Override
	public String toString()
	{
		return String.format("ComboItem[ id=%d, description=%s]", getComboId(), getDescription());
	}
	
	/**
	 * 
	 * @param s
	 * @return
	 */
	
	
	public static ComboItem[] readFromString(String s)
	{
		if(s==null)
			return new ComboItem[0];
		
		Pattern pattern = Pattern.compile("\\s*\\{\\s*(\\d+)\\s*\\,([^\\}]+)\\}\\s*");
		
		Matcher m = pattern.matcher( s );
		
		int pos =0;
		
		List<ComboItem> l = new ArrayList<ComboItem>();
		
		while( m.find(pos) )
		{
			ComboItem item = new ComboItem();
			item.setComboId( Integer.parseInt( m.group( 1 ) ) );
			item.setDescription( m.group( 2 )  );
			l.add( item );

			pos+= m.group().length();
		}
		
		ComboItem[] items = new ComboItem[l.size()];
		l.toArray( items );
		
		return items;
	}

}
